/**
 * 
 */
package com.tdam.g12;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

import com.tdam.g12.soporte.Constantes;
import com.tdam.g12.soporte.Contacto;
import com.tdam.g12.soporte.Email;
import com.tdam.g12.soporte.MensajeWEB;
import com.tdam.g12.soporte.Telefono;
import com.tdma.g12.provider.SMSWebProvider;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * @author User
 *
 */
public class MenuContacto extends Activity {
	
	private static final int DIALOG_ALTA_USUARIO = 7;
	
	private EditText txtUsuarioWeb;
	private String nomUsuario;
	
	private ImageView imgAvatar;
	private TextView txtContacto;
	private Button btnSMSWeb;
	private Button btnLlamar;
	private Button btnSMS;
	private Button btnMail;
	private Button btnHistorial;
	
	
	private Contacto contacto = null;
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu_contacto);
		
		imgAvatar = (ImageView)findViewById(R.id.imgAvatarMenuContacto);
		txtContacto = (TextView)findViewById(R.id.txtNombre);
		btnSMSWeb = (Button)findViewById(R.id.btnSMSWeb);
		btnLlamar = (Button)findViewById(R.id.btnLlamar);
		btnSMS = (Button)findViewById(R.id.btnSMS);
		btnMail = (Button)findViewById(R.id.btnMail);
		btnHistorial = (Button)findViewById(R.id.btnHistorial);
		
		Bundle bundle = getIntent().getExtras();
		loadContactoSeleccionado(bundle);
		//loadContactoSeleccionado(savedInstanceState);
		setListener();
		
	}

	private void loadContactoSeleccionado(Bundle bundle) {

		if (bundle != null) 
		{
			String idExterno = bundle.getString(Constantes.ID_CONTACTO);
			String nombre = bundle.getString(Constantes.NOMBRE);
			String avatar = String.valueOf(bundle.getString(Constantes.AVATAR));
			
			if (idExterno != null) 
			{
				contacto = new Contacto(nombre, 0, idExterno); // Integer.parseInt(avatar),
																// idExterno);
				loadTelefonos(contacto);
				loadEmails(contacto);
				loadUsuarioSMSWeb(contacto); 
				
				showContacto();
			}
		}
	}
	
	public void loadTelefonos(Contacto contacto) 
    {	
		Cursor cursor = getContentResolver().query( //inicio query
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
				new String[] {  contacto.getIdExterno() }, null); //fin query
		
		while (cursor.moveToNext()) 
		{
			contacto.addTelefono(new Telefono(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)), 
									   cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))));
		}
		
		cursor.close();
	}
	
	private void loadEmails(Contacto contacto) 
	{
		Cursor cursor = getContentResolver().query( //inicio query
				ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
				ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
				new String[] {  contacto.getIdExterno() }, null); //fin query
		
		while (cursor.moveToNext()) 
		{
			contacto.addMail(new Email(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)), 
									   cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE))));
		}
		
		cursor.close();
	}
	
	private void loadUsuarioSMSWeb(Contacto contacto) 
	{
		Cursor cursor = getContentResolver().query( //inicio query
    			SMSWebProvider.CONTENT_URI, null, null,
				//Constantes.ID_CONTACTO + " = ?",
				new String[] { contacto.getIdExterno() }, null); //fin query
		
		while (cursor.moveToNext()) 
		{
			contacto.addTelefono(new Telefono( cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)),
											   cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))));
		}
		
		cursor.close();
	}
	
	private void showContacto() 
	{
		if (contacto == null) 
		{
			return;
		}

		txtContacto.setText(contacto.getNombre());
		imgAvatar.setImageResource(contacto.getAvatar());
		txtContacto.setTag(contacto.getIdExterno());
	}
	
	private void setListener ()
	{
		btnSMSWebListener();
		btnLlamarListener();
		btnSMSListener();
		btnMailListener();
		btnHistorialListener();
		txtContactoListener();
	}
	
	private void txtContactoListener ()
	{
		txtContacto.setOnLongClickListener(new View.OnLongClickListener()
		{			
			@Override
			public boolean onLongClick(View v)
			{
				// TODO Auto-generated method stub
				showDialog(DIALOG_ALTA_USUARIO);
				return false;
			}
		});
	}
	
	private void btnSMSWebListener ()
	{
		btnSMSWeb.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
        		
   			}
		});
	}
	
	private void btnLlamarListener ()
	{
		btnLlamar.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	private void btnSMSListener ()
	{
		btnSMS.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	private void btnMailListener ()
	{
		btnMail.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	private void btnHistorialListener()
	{
		btnHistorial.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				if (contacto != null) {
					Intent intent = new Intent(MenuContacto.this, ListaHistorial.class);
					intent.putExtra(Constantes.ID_CONTACTO,  contacto.getIdExterno());//setea el valor dentro de un HASH
					intent.putExtra(Constantes.NOMBRE, contacto.getNombre());
					intent.putExtra(Constantes.AVATAR, contacto.getAvatar());
					startActivity(intent);
				}
			}
		});
	}
	
	protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_ALTA_USUARIO:
            LayoutInflater inflater = LayoutInflater.from(this);
            final View usuarioEnterView = inflater.inflate(R.layout.usuario_mje_web, null);
            return new AlertDialog.Builder(MenuContacto.this)
            .setView(usuarioEnterView)
            .setPositiveButton(R.string.btnOK, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	txtUsuarioWeb = (EditText)usuarioEnterView.findViewById(R.id.txtUsuarioAlta);
                	// Usuario ha pulsado OK 
                	try {
                		nomUsuario = txtUsuarioWeb.getText().toString();
                		contacto.addMjeWeb(new MensajeWEB(nomUsuario, Integer.parseInt(contacto.getIdExterno())));
                		
                		ByteArrayOutputStream contactoByte = new ByteArrayOutputStream();
                		try{
                			ObjectOutputStream oos = new ObjectOutputStream(contactoByte);
                			oos.writeObject(contacto);
                			}
                		catch(java.io.IOException ioe){
                			ioe.getMessage();
                			} 
                		
                		ContentValues cv = new ContentValues();
                		cv.put(Constantes.CONTACTO_WEB, contactoByte.toByteArray());
                		Uri uri = getContentResolver().insert(SMSWebProvider.CONTENT_URI, cv);
					} catch (Exception e) {
						// TODO: handle exception
						String mensaje = e.getMessage();
						// mostrarMensaje("ERROR: " + mensaje);
					}
                }
            })
            .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                }
            })
            .create();
        }
        return null;
    }
	
}
